class PaymentsController < ApplicationController
  # GET /payments
  # GET /payments.json
  def index

   if params.has_key? ("account_id") and  params.has_key? ("category_id")
     @payments = Payment.find_all_by_account_id_and_category_id(params[:account_id], params[:category_id] )
     render json: @payments
   else
     @payments = Payment.all

     respond_to do |format|
       format.html # index.html.erb
       format.json { render json: @payments }
     end
   end
  end

  # GET /payments/1
  # GET /payments/1.json
  def show
    @payment = Payment.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @payment }
    end
  end

  # GET /payments/new
  # GET /payments/new.json
  def new
    @payment = Payment.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @payment }
    end
  end

  # GET /payments/1/edit
  def edit
    @payment = Payment.find(params[:id])
  end

  # POST /payments
  # POST /payments.json
  def create

    @payment = Payment.new(params[:payment])

    budget = AccountBudgetRule.find_by_name_and_account_id(@payment.category.name, @payment.account_id )
    if  budget.budget_limit_w_exceptions   -   budget.utilization >=  @payment.amount

           if @payment.save
             render :json => [:response => "Success, Payment Authorized "].to_json
           else
             format.html { render action: "new" }
             format.json { render json: @payment.errors, status: :unprocessable_entity }
           end
    else
      notification = Notification.new
      notification.category_id = @payment.category_id
      notification.account_id = @payment.account_id
      notification.amount =   budget.utilization +  @payment.amount - budget.budget_limit_w_exceptions
      notification.price = @payment.amount
      notification.read=false
      notification.save

      render :json => [:response => "Failure, Payment not Authorized"].to_json

    end


  end

  # PUT /payments/1
  # PUT /payments/1.json
  def update
    @payment = Payment.find(params[:id])

    respond_to do |format|
      if @payment.update_attributes(params[:payment])
        format.html { redirect_to @payment, notice: 'Payment was successfully updated.' }
        format.json { head :ok }
      else
        format.html { render action: "edit" }
        format.json { render json: @payment.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /payments/1
  # DELETE /payments/1.json
  def destroy
    @payment = Payment.find(params[:id])
    @payment.destroy

    respond_to do |format|
      format.html { redirect_to payments_url }
      format.json { head :ok }
    end
  end
end
